﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace KD.Sms.SerialServer
{
    public class XGA2880RS10 : IDisposable
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public XGA2880RS10(string ip, int port)
        {
            E_IP = ip;
            E_Port = port;
            E_Interval = 500;
        }
        /// <summary>
        /// 当前类名
        /// </summary>
        public static string _strClassName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;

        /// <summary>
        /// 
        /// </summary>
        public string E_IP { set; get; }
        /// <summary>
        /// 
        /// </summary>
        public int E_Port { set; get; }

        public int E_Interval { set; get; }

        /// <summary>
        /// 同步返回事件
        /// </summary>
        public event EventHandler<CommonEventArgs> ReadEvent;
        /// <summary>
        /// 重量读取线程
        /// </summary>
        private Thread _thrdRead;
        /// <summary>
        /// 线程控制开关
        /// </summary>
        private bool _bRun = false;
        /// <summary>
        /// TCP客户端对象
        /// </summary>
        private TcpClient tcpClient;
        /// <summary>
        /// TCP数据操作流
        /// </summary>
        private NetworkStream ntwStream;

        /// <summary>
        /// 
        /// </summary>
        public void DoRead()
        {
            _bRun = true;
            _thrdRead = new Thread(new ThreadStart(DoReadListening));
            _thrdRead.IsBackground = true;
            _thrdRead.Start();
        }

        /// <summary>
        /// 停止光幕数据读取
        /// </summary>
        public void DoStop()
        {
            _bRun = false;
            System.Threading.Thread.Sleep(E_Interval);
            if (_thrdRead != null)
                _thrdRead.Abort();
        }

        /// <summary>
        /// 光幕数据读取
        /// </summary>
        private void DoReadListening()
        {
            if (NetJudger.DoJudge(E_IP))
            {
                System.Threading.Thread.Sleep(1500);
                Log.LogHelper.DoWriteLogTypeClass(Log.LogType.Program, _strClassName, "尝试连接红外光幕");
                try
                {
                    tcpClient = new TcpClient();
                    tcpClient.Connect(E_IP, E_Port);
                    ntwStream = tcpClient.GetStream();
                    if (ntwStream.CanRead)
                    {
                        //接收状态,长度<1024字节
                        byte[] bytes, _arrValue;
                        string _strReadData, _strAnalysis;
                        int byteLength;
                        while (_bRun)
                        {
                            try
                            {
                                bytes = new Byte[1024];
                                _strReadData = string.Empty;
                                byteLength = ntwStream.Read(bytes, 0, bytes.Length);
                                if (byteLength > 0)
                                {
                                    _strReadData = "";
                                    for (int i = 0; i < bytes.Length; i++)
                                    {
                                        _strReadData = _strReadData + bytes[i].ToString("X").PadLeft(2, '0') + " ";
                                    }
                                    if (_strReadData.IndexOf("AA AA 00", 0) >= 0)
                                    {
                                        _strAnalysis = _strReadData.Substring(_strReadData.IndexOf("AA AA 00", 0), 26);
                                        _arrValue = new byte[4]
                                        {
                                            Convert.ToByte(_strAnalysis.Substring(9, 2).ToString(), 16),
                                            Convert.ToByte(_strAnalysis.Substring(12, 2).ToString(), 16),
                                            Convert.ToByte(_strAnalysis.Substring(15, 2).ToString(), 16),
                                            Convert.ToByte(_strAnalysis.Substring(18, 2).ToString(), 16)
                                        };
                                        EventHelper.DispatchEventAsync<CommonEventArgs>(this, this.ReadEvent, new CommonEventArgs(_arrValue));
                                    }
                                }
                                System.Threading.Thread.Sleep(500);
                            }
                            catch (Exception ex)
                            {
                                EventHelper.DispatchEventAsync<CommonEventArgs>(this, this.ReadEvent, new CommonEventArgs(ex.StackTrace));
                                Log.LogHelper.DoWriteLogTypeClass(Log.LogType.Program, _strClassName, "红外光幕数据采集异常,系统尝试重连!!");
                                Log.LogHelper.DoWriteLogTypeClass(Log.LogType.Program, _strClassName, ex.ToString());
                                if (ex.ToString().IndexOf("远程主机强迫关闭了一个现有的连接") >= 0)
                                {
                                    System.Threading.Thread.Sleep(10000);
                                    try
                                    {
                                        ntwStream.Close();
                                        tcpClient.Close();
                                        System.Threading.Thread.Sleep(2000);

                                        tcpClient = new TcpClient();
                                        tcpClient.Connect(E_IP, E_Port);
                                        ntwStream = tcpClient.GetStream();
                                        System.Threading.Thread.Sleep(2000);
                                        Log.LogHelper.DoWriteLogTypeClass(Log.LogType.Program, _strClassName, "红外光幕数据采集异常，重连成功");
                                    }
                                    catch (Exception exx)
                                    {
                                        Log.LogHelper.DoWriteLogTypeClass(Log.LogType.Program, _strClassName, "红外光幕数据读取失败，系统重连出错");
                                        Log.LogHelper.DoWriteLogTypeClass(Log.LogType.Program, _strClassName, exx.ToString());
                                    }
                                }
                            }
                        }
                        ntwStream.Close();
                        tcpClient.Close();
                    }
                    else
                    {
                        ntwStream.Close();
                        tcpClient.Close();
                    }
                }
                catch (Exception ex)
                {
                    EventHelper.DispatchEventAsync<CommonEventArgs>(this, this.ReadEvent, new CommonEventArgs(ex.StackTrace));
                }
            }
            else
                EventHelper.DispatchEventAsync<CommonEventArgs>(this, this.ReadEvent, new CommonEventArgs(9999));
        }



        #region 释放托管资源
        private bool IsDisposed = false;
        /// <summary>
        /// 释放资源
        /// </summary>
        public virtual void Dispose()
        {
            if (!this.IsDisposed)
            {
                try
                {
                    if (_thrdRead != null)
                    {
                        _bRun = false;
                        System.Threading.Thread.Sleep(200);
                        _thrdRead.Abort();
                    }
                    ntwStream.Close();
                    tcpClient.Close();
                }
                finally
                {
                    this.IsDisposed = true;
                    GC.SuppressFinalize(this);
                }
            }
        }
        #endregion


    }
}
